package com.qike.baoxiu.service.impl;

import com.qike.baoxiu.dto.ChangPwdDto;
import com.qike.baoxiu.dto.LoginDto;
import com.qike.baoxiu.enums.StatusEnums;
import com.qike.baoxiu.mapper.UserMapper;
import com.qike.baoxiu.pojo.User;
import com.qike.baoxiu.pojo.UserExample;
import com.qike.baoxiu.service.UserService;
import com.qike.baoxiu.tools.TokenUtil;
import com.qike.baoxiu.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Year;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TokenService tokenService;


    /**
     * 登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) throws Exception {
        LoginVo vo = new LoginVo();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andAccountEqualTo(loginDto.getAccount()).andPasswordEqualTo(loginDto.getPassword()).andStatusEqualTo(StatusEnums.NO.getEcode());
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size()>0&&users.get(0).getRole()!=2){
            vo.setUserName(users.get(0).getUserName());
            vo.setToken(tokenService.getToken(users.get(0)));
            vo.setUid(users.get(0).getId());
            return vo;
        }else {
            throw new Exception("账号密码错误");
        }

    }

    /**
     * pad登录
     *
     * @param loginDto
     * @return
     * @throws Exception
     */
    @Override
    public LoginVo PadLogin(LoginDto loginDto) throws Exception {
        LoginVo vo = new LoginVo();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andAccountEqualTo(loginDto.getAccount()).andPasswordEqualTo(loginDto.getPassword()).andStatusEqualTo(StatusEnums.NO.getEcode()).andRoleEqualTo(0);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size()>0&&users.get(0).getRole()!=null&&users.get(0).getRole().equals(1)){
            vo.setUserName(users.get(0).getUserName());
            vo.setToken(tokenService.getToken(users.get(0)));
            return vo;
        }else {
            throw new Exception("账号密码错误");
        }
    }

    /**
     * 修改密码
     *
     * @param changPwdDto
     */
    @Override
    public void changPwd(ChangPwdDto changPwdDto) throws Exception {
        Integer userId = TokenUtil.getTokenUserId();
        if (!changPwdDto.getNewPwd().equals(changPwdDto.getReNewPwd())){
            throw new Exception("两次输入密码不一致");
        }
        User user = userMapper.selectByPrimaryKey(userId);
        user.setPassword(changPwdDto.getNewPwd());
        userMapper.updateByPrimaryKeySelective(user);
    }
}
